package net.hhk.twitter;

import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import java.lang.reflect.Array;
import java.security.acl.LastOwnerException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;

import net.hhk.connect.HTTPConnect;
import net.hhk.controller.TweetAdapter;
import net.hhk.controller.TweetManager;
import net.hhk.data.Constant;
import net.hhk.data.MySharePreferences;
import net.hhk.data.Tweet;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class HomeActivity extends ListActivity {

	private TweetManager mgr;
	private TweetAdapter mAdapter;
	// private SimpleAdapter mAdapter;
	private View mLoadMoreFooter;

	private boolean mLoading;

	private static final int MSG_APPEND_MORE_ITEMS = 0;

	private static final int NUMBER_OF_ITEMS_REQUESTED = 10;
	private int currentPage = 1;
	private Context context = this;

	private int mTrunksCount = 0;
	MySharePreferences sharePre;
	Boolean isResume = false;
	public LayoutInflater inflater;
	public boolean isLongClick = false;
	public int currentLongClick = -1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		mgr = new TweetManager(getApplicationContext());
		inflater = LayoutInflater.from(this);
		mLoadMoreFooter = inflater.inflate(R.layout.profile, null);

		getListView().addFooterView(mLoadMoreFooter);
		// getListView().addHeaderView(mLoadMoreFooter);

		getListView().setOnScrollListener(mScrollListener);
		((PullToRefreshListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					public void onRefresh() {
						// Do work to refresh the list here.
						// new GetDataTask().execute();
						refreshData();

					}
				});

		mLoading = false;
		sharePre = (MySharePreferences) getApplicationContext();

		loadData();
		ListView list = getListView();

		list.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> av, View v, int pos,
					long id) {
				final LinearLayout context_menu = (LinearLayout) v
						.findViewById(R.id.context_menu);
				removeContextMenu();
				currentLongClick = pos;
				context_menu.setVisibility(View.VISIBLE);

				Tweet tweet = (Tweet) getListView().getItemAtPosition(pos);
				context_menu.removeAllViews();
				context_menu.addView(loadContextMenu(tweet));
				// mAdapter.notifyDataSetChanged();
				isLongClick = true;
				TextView text = (TextView) v.findViewById(R.id.twitMessage);
				return false;
			}
		});

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isResume = true;
		// mAdapter.clearCache();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		sharePre.setExitString("currentVisitUsername",
				sharePre.getExitString("myUsername"));
		if (isResume) {
			isResume = false;

			int isErrorTweet = sharePre.getExitInt("isErrorTweet", 0);
			if (isErrorTweet > 0) {
				mAdapter.removeItem(isErrorTweet);
				String message = "tweet not found";
				int duration = Toast.LENGTH_SHORT;

				Toast toast = Toast.makeText(context, message, duration);
				toast.show();
				sharePre.setExitInt("isErrorTweet", 0);
			}

			String favorite = sharePre.getExitString("favoriteChange");
			String unfavorite = sharePre.getExitString("unfavoriteChange");
			String retweet = sharePre.getExitString("retweetChange");
			String unretweet = sharePre.getExitString("unretweetChange");
			if (favorite.length() > 1) {
				String[] test = favorite.split(";");
				for (String string : test) {
					if (string.length() > 0) {
						int id = Integer.parseInt(string);
						mAdapter.favoriteById(true, id);
					}
				}
			}
			if (unfavorite.length() > 1) {
				String[] test = unfavorite.split(";");
				for (String string : test) {
					if (string.length() > 0) {
						int id = Integer.parseInt(string);
						mAdapter.favoriteById(false, id);
					}
				}
			}
			if (retweet.length() > 1) {
				String[] test = retweet.split(";");
				for (String string : test) {
					if (string.length() > 0) {
						int id = Integer.parseInt(string);
						mAdapter.retweetById(true, id);
					}
				}
			}
			if (unretweet.length() > 1) {
				String[] test = unretweet.split(";");
				for (String string : test) {
					if (string.length() > 0) {
						int id = Integer.parseInt(string);
						mAdapter.retweetById(false, id);
					}
				}
			}
			mAdapter.notifyDataSetChanged();
			sharePre.setExitString("favoriteChange", "");
			sharePre.setExitString("unfavoriteChange", "");
			sharePre.setExitString("retweetChange", "");
			sharePre.setExitString("unretweetChange", "");

			int isTweetDeleted = sharePre.getExitInt("isDeleteTweet", 0);
			if (isTweetDeleted > 0) {
				sharePre.setExitInt("isDeleteTweet", 0);
				mAdapter.removeItem(isTweetDeleted);
			}
			int isNewTweet = sharePre.getExitInt("isNewTweet", 0);
			if (isNewTweet > 0) {
				loadNewTweet();
				sharePre.setExitInt("isNewTweet", 0);
			}

		}

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		if (isLongClick) {
			isLongClick = false;
			return;
		}
		removeContextMenu();
		// List<Tweet> tweets = mgr.getTweets();
		Tweet tweet = (Tweet) l.getItemAtPosition(position);
		int tweetid = tweet.getTweetId();
		String tweetUser = tweet.getNameRweet();
		Boolean isfavor = tweet.getIsMyFavorite();
		Boolean isretweet = tweet.getIsMyRetweet();
		Intent i = new Intent(getApplicationContext(), ViewTweetActivity.class);
		Bundle b = new Bundle();
		b.putInt("id", tweetid);
		b.putString("retweetUser", tweetUser);
		b.putBoolean("isfavorite", isfavor);
		b.putBoolean("isretweet", isretweet);
		sharePre.setExitString("currentVisitUsername", tweet.getUserName());
		// ScrollView scrollView;
		// scrollView.sc

		// Your id
		i.putExtras(b); // Put your id to your next Inten
		startActivity(i);
	}

	private void loadData() {
		AsyncTask<String, Void, List<Tweet>> asyncTask = new AsyncTask<String, Void, List<Tweet>>() {
			// private ProgressDialog progressDialog = new ProgressDialog(
			// HomeActivity.this);

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// progressDialog.setTitle("Loading Tweets");
				// if (!progressDialog.isShowing()) {
				// progressDialog.show();
				// }
			}

			@Override
			protected List<Tweet> doInBackground(String... params) {
				// Following actions will be done in background
				return mgr.getSocialFeed(Constant.TIMELINE, 0, 1,
						NUMBER_OF_ITEMS_REQUESTED);
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<Tweet> result) {
				super.onPostExecute(result);
				// if (progressDialog.isShowing()) {
				// progressDialog.hide();
				// }
				mAdapter = new TweetAdapter(HomeActivity.this, result);
				mAdapter.notifyDataSetChanged();
				setListAdapter(mAdapter);
				if (mAdapter.getCount() < NUMBER_OF_ITEMS_REQUESTED) {
					if (getListView().getFooterViewsCount() > 0)
						getListView().removeFooterView(mLoadMoreFooter);
					mLoading = false;
				}

			}
		};
		asyncTask.execute("Saurabh");
	}

	private void refreshData() {
		AsyncTask<String, Void, List<Tweet>> asyncTask = new AsyncTask<String, Void, List<Tweet>>() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected List<Tweet> doInBackground(String... params) {
				return mgr.getSocialFeed(Constant.TIMELINE, 0, 1,
						NUMBER_OF_ITEMS_REQUESTED);
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<Tweet> result) {
				((PullToRefreshListView) getListView()).onRefreshComplete();
				super.onPostExecute(result);
				mAdapter = new TweetAdapter(HomeActivity.this, result);
				mAdapter.notifyDataSetChanged();
				setListAdapter(mAdapter);
				currentPage = 1;
				mLoading = false;
				if (getListView().getFooterViewsCount() == 0) {
					getListView().addFooterView(mLoadMoreFooter);
				}

			}
		};
		asyncTask.execute("Saurabh");
	}

	private void loadMoreItems() {
		mLoading = true;

		new Thread() {
			public void run() {
				try {
					// in this example, we just simply wait for 2 seconds
					Thread.sleep(2000);
					Message msg = mMainhandler.obtainMessage(
							MSG_APPEND_MORE_ITEMS, generateList());
					mMainhandler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	private void loadNewTweet() {
		AsyncTask<String, Void, List<Tweet>> asyncTask = new AsyncTask<String, Void, List<Tweet>>() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();

			}

			@Override
			protected List<Tweet> doInBackground(String... params) {
				return mgr.getNewTweet(Constant.GET_NEW_TWEET);
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<Tweet> result) {
				super.onPostExecute(result);
				mAdapter.appendHeadItem((ArrayList<Tweet>) result);
				getListView().setSelection(result.size());

			}
		};
		asyncTask.execute("Saurabh");
	}

	private Handler mMainhandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_APPEND_MORE_ITEMS:
				ArrayList newData = (ArrayList) msg.obj;
				if (mAdapter == null) {
					mAdapter = new TweetAdapter(HomeActivity.this, newData);
					setListAdapter(mAdapter);
				} else {

					mAdapter.appendItems(newData);
				}

				if (newData.size() < NUMBER_OF_ITEMS_REQUESTED) {
					getListView().removeFooterView(mLoadMoreFooter);
				}
				mLoading = false;
				break;

			}

		}
	};

	private ArrayList generateList() {
		currentPage++;

		return (ArrayList<Tweet>) mgr.getSocialFeed(Constant.TIMELINE, 0,
				currentPage, NUMBER_OF_ITEMS_REQUESTED);
	}

	private ArrayList getNewTweet() {
		return (ArrayList<Tweet>) mgr.getNewTweet(Constant.GET_NEW_TWEET);
	}

	private void checkLoadMore() {
		if (mLoading)
			return;

		/*
		 * if the loading footer is still there, then we will load more items
		 */
		if (getListView().getFooterViewsCount() != 0) {
			loadMoreItems();
		}
	}

	private OnScrollListener mScrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// We have nothing to do with this right now
			removeContextMenu();
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {

			if (view.getLastVisiblePosition() >= 0) {
				if (view.getLastVisiblePosition() >= (totalItemCount - 1)) {

					checkLoadMore();
				}
			}
		}
	};

	public void removeContextMenu() {
		if (currentLongClick == -1)
			return;
		int firstPosition = getListView().getFirstVisiblePosition();
		int wantedChild = currentLongClick - firstPosition;
		// Say, first visible position is 8, you want position 10, wantedChild
		// will now be 2
		// So that means your view is child #2 in the ViewGroup:
		if (wantedChild < 0 || wantedChild >= getListView().getChildCount()) {
			return;
		}
		// Could also check if wantedPosition is between
		// listView.getFirstVisiblePosition() and
		// listView.getLastVisiblePosition() instead.
		View v = getListView().getChildAt(wantedChild);

		final LinearLayout context_menu = (LinearLayout) v
				.findViewById(R.id.context_menu);
		context_menu.removeAllViews();
		context_menu.setVisibility(View.GONE);
		TextView text = (TextView) v.findViewById(R.id.twitMessage);

		currentLongClick = -1;

	}

	public View loadContextMenu(Tweet tweet) {
		View row = null;
		final Tweet twit = tweet;
		String myname = sharePre.getExitString("myUsername");
		if (!tweet.getUserName().equals(myname)) {
			row = inflater.inflate(R.layout.user_context_menu, null);
			final Button rt = (Button) row
					.findViewById(R.id.tweet_dt_retweet_button);
			if (tweet.getIsMyRetweet()) {
				rt.setBackgroundResource(R.drawable.ic_action_rt_on_default);
			}
			rt.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					String title;
					String retweet_status;
					if (!twit.getIsMyRetweet()) {
						title = "Are you sure want to retweet this tweet";
						retweet_status ="Retweet";
					}
					else {
						title = "Are you sure want to unretweet this tweet";
						retweet_status ="UnRetweet";
					}

					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							context);

					alertDialogBuilder
							.setMessage(
									title)
							.setCancelable(false)
							.setPositiveButton(retweet_status,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											if (twit.getIsMyRetweet()) {
												unRetweet(twit.getTweetId());
												twit.setIsMyRetweet(false);
											} else {
												retweet(twit.getTweetId());
												twit.setIsMyRetweet(true);
											}
											removeContextMenu();
											mAdapter.notifyDataSetChanged();
										}
									})
							.setNeutralButton("Quote",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											sharePre.setExitString(
													Constant.VISIT_USER_NAME,
													twit.getUserName());
											Intent i = new Intent(
													getApplicationContext(),
													WriteTweetActivity.class);
											Bundle b = new Bundle();

											b.putInt("isReply", 0);
											b.putString("mention", "");
											b.putString("quote",
													twit.getTweetText());
											sharePre.setExitString(
													"currentVisitUsername",
													twit.getUserName());

											// Your id
											i.putExtras(b);
											startActivity(i);
										}
									})
							.setNegativeButton("Cancel",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// if this button is clicked, just
											// close
											// the dialog box and do nothing
											dialog.cancel();
										}
									});

					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();

					// show it
					alertDialog.show();

				}
			});

		} else {
			row = inflater.inflate(R.layout.my_context_menu, null);
			Button delete = (Button) row.findViewById(R.id.tweet_dt_delete);
			delete.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							context);

					alertDialogBuilder
							.setMessage(
									"Are you sure want to delete this Tweet")
							.setCancelable(false)
							.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											deleteTweet(twit.getTweetId());
											mAdapter.removeItem(twit
													.getTweetId());
											removeContextMenu();
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});

					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();

					// show it
					alertDialog.show();

				}
			});

		}
		Button favor = (Button) row.findViewById(R.id.tweet_dt_favor);
		favor.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (twit.getIsMyFavorite()) {
					unFovorite(twit.getTweetId());
					// Tweet tweet = (Tweet)
					// getListView().getItemAtPosition(currentLongClick);
					twit.setIsMyFavorite(false);
				} else {
					favorite(twit.getTweetId());
					twit.setIsMyFavorite(true);
				}
				removeContextMenu();
				mAdapter.notifyDataSetChanged();
			}
		});
		if (tweet.getIsMyFavorite()) {
			favor.setBackgroundResource(R.drawable.ic_action_fave_on_default);
		}

		Button reply = (Button) row.findViewById(R.id.tweet_dt_reply);
		reply.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				sharePre.setExitString(Constant.VISIT_USER_NAME,
						twit.getUserName());
				Intent i = new Intent(getApplicationContext(),
						WriteTweetActivity.class);
				Bundle b = new Bundle();

				b.putInt("isReply", twit.getTweetId());
				b.putString("mention", "");
				sharePre.setExitString("currentVisitUsername",
						twit.getUserName());

				// Your id
				i.putExtras(b);
				startActivity(i);

			}
		});

		return row;
	}

	public void favorite(int tweetid) {
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		postParameters.add(new BasicNameValuePair("tweetid", Integer
				.toString(tweetid)));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_FAVORITE, postParameters);

	}

	public void unFovorite(int tweetid) {
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		postParameters.add(new BasicNameValuePair("tweetid", Integer
				.toString(tweetid)));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http
				.doConnect(Constant.POST_UNFAVORITE, postParameters);

	}

	public void retweet(int tweetid) {

		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		postParameters.add(new BasicNameValuePair("tweetid", Integer
				.toString(tweetid)));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_RETWEET, postParameters);
	}

	public void unRetweet(int tweetid) {
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		postParameters.add(new BasicNameValuePair("tweetid", Integer
				.toString(tweetid)));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_UNRETWEET, postParameters);
	}

	public void deleteTweet(int tweetid) {
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		postParameters.add(new BasicNameValuePair("tweetid", Integer
				.toString(tweetid)));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.DELETE_TWEET, postParameters);
	}

}